package com.sprouting.ops.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sprouting.ops.annotations.invoke.IdempotentSingle;
import com.sprouting.ops.interfaces.AddGroup;
import com.sprouting.ops.interfaces.ConstantBase;
import com.sprouting.ops.interfaces.UpdGroup;
import com.sprouting.ops.model.DromaraFileStorage;
import com.sprouting.ops.model.OpsComponent;
import com.sprouting.ops.model.ResultJson;
import com.sprouting.ops.model.bo.OpsComponentBo;
import com.sprouting.ops.model.qo.OpsComponentQo;
import com.sprouting.ops.model.vo.OpsAppVo;
import com.sprouting.ops.model.vo.OpsComponentVo;
import com.sprouting.ops.service.DromaraFileStorageService;
import com.sprouting.ops.service.OpsComponentService;
import com.sprouting.ops.utils.CheckTool;
import com.sprouting.ops.utils.EntityTool;
import com.sprouting.ops.utils.IdTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (组件信息)表控制层
 *
 * @author longx
 * @since 2023-11-20 22:49:09
 */
@Slf4j
@RestController
@RequestMapping("opsComponent")
public class OpsComponentController {

    @Autowired
    private OpsComponentService opsComponentService;
    @Resource
    private DromaraFileStorageService dromaraFileStorageService;


    /**
     * 根据产品id查询组件
     * @param productId 产品id
     * @return
     */
    @PostMapping("getComponentByProductId")
    public ResultJson getComponentByProductId(String productId){
        if (CheckTool.checkNull(productId)){
            return ResultJson.errorCheck();
        }

        List<OpsComponentVo> componentList = opsComponentService.getComponentByProductId(productId);
        return ResultJson.success(componentList);
    }

    /**
     * 获取可绑定的组件
     * @return
     */
    @PostMapping("getBindableComponent")
    public ResultJson getBindableComponent(){
        return ResultJson.success(opsComponentService.getBindableComponent());
    }

    /**
     * 逻辑删除
     * @param opsComponentId 主键
     * @return
     */
    @IdempotentSingle
    @PostMapping("delOpsComponent")
    public ResultJson delOpsComponent(String opsComponentId){
        if (CheckTool.checkNull(opsComponentId)){
            return ResultJson.errorCheck();
        }

        OpsComponent opsComponent = opsComponentService.getById(opsComponentId);
        if (opsComponent == null){
            return ResultJson.success();
        }


        DromaraFileStorage opsUploadFile = dromaraFileStorageService.delFileBefore(opsComponent.getIco());
        // 逻辑删除
        opsComponentService.delOpsComponent(opsComponent, opsUploadFile);
        return ResultJson.success();
    }

    /**
     * 分页查询
     * @param query 查询参数
     * @return
     */
    @RequestMapping("getOpsComponentPageList")
    public ResultJson getOpsComponentPageList(OpsComponentQo query){
        if (query == null){
            query = new OpsComponentQo();
        }
        Page page = query.getPage();
        Page<OpsComponentVo> opsComponentPageList = opsComponentService.getOpsComponentPageList(page, query);
        if (CollUtil.isEmpty(opsComponentPageList.getRecords())){
            return ResultJson.success(opsComponentPageList);
        }

        for (OpsComponentVo record : opsComponentPageList.getRecords()) {
            if (StrUtil.isEmpty(record.getOs())){
                continue;
            }

            // 转换 os 为集合
            List<Integer> list = Arrays.stream(record.getOs().split(",")).map(Integer::parseInt).collect(Collectors.toList());
            record.setOsList(list);
            record.setOsStr(getOs(list));
        }
        return ResultJson.success(opsComponentPageList);
    }

    /**
     * 保存
     * @param opsComponentBo 保存对象
     * @return
     */
    @IdempotentSingle
    @PostMapping("saveOpsComponent")
    public ResultJson saveOpsComponent(@Validated(AddGroup.class) OpsComponentBo opsComponentBo){
        String msg = checkOpsComponent(opsComponentBo);
        if (msg != null){
            return ResultJson.error(msg);
        }

        OpsComponent opsComponent = BeanUtil.copyProperties(opsComponentBo, OpsComponent.class);
        opsComponent.setId(IdTool.getId());
        EntityTool.saveBase(opsComponent);


        // 处理图片
        DromaraFileStorage opsUploadFile = dromaraFileStorageService.toProductionBefore(opsComponent.getIco(), opsComponent.getId(), ConstantBase.FileSourceType.COMPONENT_ICO);

        opsComponentService.saveOpsComponent(opsComponent, opsUploadFile);
        return ResultJson.success(opsComponent);
    }

    /**
     * 更新
     * @param opsComponentBo 更新对象
     * @return
     */
    @IdempotentSingle
    @PostMapping("updOpsComponent")
    public ResultJson updOpsComponent(@Validated(UpdGroup.class) OpsComponentBo opsComponentBo){
        String msg = checkOpsComponent(opsComponentBo);
        if (msg != null){
            return ResultJson.error(msg);
        }

        OpsComponent opsComponent = BeanUtil.copyProperties(opsComponentBo, OpsComponent.class);
        // 查询到旧的
        OpsComponent oldDb = opsComponentService.getById(opsComponent.getId());
        DromaraFileStorage[] uploadFileArray = dromaraFileStorageService.updFileBefore(opsComponent.getIco(), oldDb.getIco(), opsComponent.getId(), ConstantBase.FileSourceType.COMPONENT_ICO);

        EntityTool.updBase(opsComponent);
        opsComponentService.updOpsComponent(opsComponent, uploadFileArray);
        return ResultJson.success(opsComponent);
    }

    /**
     * 检查
     * @param opsComponentBo 校验对象
     * @return 非null则有异常
     */
    private String checkOpsComponent(OpsComponentBo opsComponentBo){
        OpsComponent nameDb = opsComponentService.getByNameFilterId(opsComponentBo.getName(), opsComponentBo.getId());
        if (nameDb != null){
            return "组件名称已注册，请勿重复添加";
        }

        if (CollUtil.isEmpty(opsComponentBo.getOsList())){
            List<Integer> osList = new ArrayList<>();
            osList.add(ConstantBase.OsType.LINUX);
            osList.add(ConstantBase.OsType.WINDOWS);
            osList.add(ConstantBase.OsType.MAC);
            osList.add(ConstantBase.OsType.UNIX);
            // osList.add(ConstantBase.OsType.YHQL);
            // osList.add(ConstantBase.OsType.TXUOS);
            // osList.add(ConstantBase.OsType.SD);
            // osList.add(ConstantBase.OsType.OULA);
            // osList.add(ConstantBase.OsType.ZXXZD);
            // osList.add(ConstantBase.OsType.HQ);
            // osList.add(ConstantBase.OsType.HARMONY);
            // osList.add(ConstantBase.OsType.ZBQL);
            opsComponentBo.setOs(StrUtil.join(",", osList));

        } else {
            opsComponentBo.setOs(StrUtil.join(",", opsComponentBo.getOsList()));
        }

        return null;
    }

    /**
     * 获取转中文后的系统类型
     * @param list 选中的类型
     * @return
     */
    private String getOs(List<Integer> list){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i ++){
            Integer i1 = list.get(i);
            sb.append(ConstantBase.OsType.MAP.get(i1));
            if (i != list.size() - 1){
                sb.append(",");
            }
        }

        return sb.toString();
    }
}

